package com.sea.supply.service.impl;


import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.ObjectMetadata;
import com.codecrane.core.util.DateUtils;
import com.sea.data.service.OrderDetailService;
import com.sea.finance.service.PaymentIncreaseLossService;
import com.sea.operate.entity.RelatedSku;
import com.sea.supply.entity.*;
import com.sea.supply.mapper.ProduceMapper;
import com.sea.supply.service.*;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.nio.charset.Charset;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

/**
 * @author 陈鸿飞
 */
@Service
public class ProduceServiceImpl implements ProduceService {

    @Autowired
    private ProduceMapper produceMapper;
    @Autowired
    private ProduceRecordService produceRecordService;
    @Autowired
    private ProduceDetailService produceDetailService;
    @Autowired
    private BuyService buyService;
    @Autowired
    private PaymentIncreaseLossService paymentIncreaseLossService;

    @Autowired
    private ProduceService produceService;
    @Autowired
    private ProducePaymentService producePaymentService;

    @Override
    public int save(Produce produce) {
        return produceMapper.insert(produce);
    }

    @Override
    public Integer getMaxId() {
        return produceMapper.getMaxId();
    }

    @Override
    public List<Produce> findByCnd(Produce produce) {
        return produceMapper.findByCnd(produce);
    }

    @Override
    public List<Produce> findByPayment(Produce produce) {
        return produceMapper.findByPayment(produce);
    }

    @Override
    public int updateProduceTotal(Integer id) {
        return produceMapper.updateProduceTotal(id);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public int usave(Produce produce) {
        //预付款设置
        if(null != produce.getFlag()){
            Produce pro = produceService.findById(produce.getId());
            if(produce.getProducePayment()>=pro.getProduceTotalMoney()){
                throw new RuntimeException("预付款不能大于付款总额!");
            }
            ProducePayment producePayment = new ProducePayment();
            producePayment.setProduceId(produce.getId());
            if(produce.getProducePayment().equals(0.00)){
                producePayment.setFlag(1);
            }else{
                producePayment.setFlag(0);
            }
            producePayment.setProducePayment(produce.getProducePayment());
            producePayment.setProduceRemark("预付款");
            producePayment.setProduceIsCheck("否");
            producePayment.setProduceCheckMoney(0.00);
            producePayment.setProduceUnusualMoney(0.00);
            producePaymentService.save(producePayment);
            paymentIncreaseLossService.updateDetail(producePayment.getId(), DateUtils.dateToString(new Date(),"yyyy-MM-dd"), produce.getProducePayment());
            return produceMapper.update(produce);
        }
        //新增操作记录
        produceRecordService.save(produce.getId(),produce.getProduceStatus(),produce.getProduceRemark());
        //作废
        if(produce.getProduceStatus().equals(5)){
            List<ProduceDetail> list = produceDetailService.findByProduceId(produce.getId());
            for(ProduceDetail detail:list){
                Buy buy=new Buy();
                buy.setId(detail.getBuyId());
                buy.setFlag(1);
                buyService.usave(buy);
            }
        }
        //审核通过如果改过数量则更新原有数量
        if(produce.getProduceStatus().equals(3)){
            List<ProduceDetail> list = produceDetailService.findByProduceId(produce.getId());
            for(ProduceDetail detail:list){
                Buy byId = buyService.findById(detail.getBuyId());
                if(!byId.getBuyNumber().equals(detail.getProduceTotal())){
                    Buy buy=new Buy();
                    buy.setId(detail.getBuyId());
                    buy.setBuyNumber(byId.getBuyNumber()-detail.getProduceTotal());
                    buy.setFlag(0);
                    buyService.usave(buy);
                }
            }
        }
        return produceMapper.update(produce);
    }

    @Override
    public int usaveAgreement(Produce produce) {
        return produceMapper.update(produce);
    }

    @Override
    public Produce findById(Integer id) {
        return produceMapper.findById(id);
    }

    @Override
    public List<Produce> findStatusNumber(Integer status) {
        List<Produce> list=new ArrayList<>();
        List<Produce> statusList = produceMapper.findStatusNumber();
        if(null!=status && status>0){
            for(Produce order:statusList){
                if(order.getProduceStatus().equals(status)){
                    list.add(order);
                    break;
                }
            }
            return list;
        }else{
            return statusList;
        }
    }

    @Override
    public List<Produce> findRefusedPo() {
        return produceMapper.findRefusedPo();
    }

    @Override
    public int updateRefused(String produceNo) {
        return produceMapper.updateRefused(produceNo);
    }

    @Override
    public List<Produce> findTotalByDetailId(Integer id) {
        return produceMapper.findTotalByDetailId(id);
    }

    @Override
    public Produce findIdByPo(String produceNo) {
        return produceMapper.findIdByPo(produceNo);
    }

    @Override
    public Integer updateChannelName() {
        return produceMapper.updateChannelName();
    }

    @Override
    public Integer updatePaymentRemark(Produce produce) {
        return produceMapper.updatePaymentRemark(produce);
    }

    @Override
    public void rollBack(Integer produceId) {
        List<ProduceDetail> produceList = produceDetailService.findByProduceId(produceId);
        if(null != produceList && produceList.size()>0){
            for (ProduceDetail produceDetail:produceList){
                Buy buy=new Buy();
                buy.setId(produceDetail.getBuyId());
                buy.setFlag(0);
                buyService.usave(buy);
            }

            //设置状态为作废
            Produce produce=new Produce();
            produce.setProduceStatus(34);
            produce.setId(produceId);
            usave(produce);
        }

    }

    @Override
    public Integer updateReadyPayment(Integer produceId) {
        return produceMapper.updateReadyPayment(produceId);
    }

    public static void inputStreamToFile(InputStream ins, File file) {
        try {
            OutputStream os = new FileOutputStream(file);
            int bytesRead = 0;
            byte[] buffer = new byte[8192];
            while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            os.flush();
            os.close();
            ins.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void importProduceAgreement(MultipartFile file, String fileName) throws Exception {
        File zipFile = null;
        String errMsg="";
        if (file.equals("") || file.getSize() <= 0) {
            file = null;
        } else {
            InputStream ins = null;
            try {
                ins = file.getInputStream();
                zipFile = new File(file.getOriginalFilename());
                inputStreamToFile(ins, zipFile);
                ZipFile zip = new ZipFile(zipFile, Charset.forName("GBK"));
                for (Enumeration enumeration = zip.entries(); enumeration.hasMoreElements(); ) {
                    ZipEntry entry = (ZipEntry) enumeration.nextElement();
                    if (entry.isDirectory()) {
                        continue;
                    }
                    //文件名
                    String filename1 = entry.getName();
                    int lastIndex = filename1.lastIndexOf(".");

                    //PO号
                    String produceNo = filename1.substring(0, lastIndex);

                    Produce produce = findIdByPo(produceNo);
                    if(null==produce){
                        errMsg+="PO【"+produceNo+"】不存在！<br/>";
                        continue;
                    }
                    InputStream inputStream = zip.getInputStream(entry);
                    String url = uploadProduceAgreementFile(filename1, inputStream);
                    produce.setProduceAgreementFile(url);
                    produceMapper.update(produce);
                    inputStream.close();

                }
            } catch (IOException e) {
                e.printStackTrace();

            } finally {
                if (ins != null) {
                    ins.close();
                }
            }
        }
    }

    @Override
    public String uploadProduceAgreementFile(String fileName, InputStream newPdfInputStream) {
        OSSClient ossClient=new OSSClient("http://oss-cn-beijing.aliyuncs.com",
                "LTAI4G55LJEk8nARtrjYngou",
                "XPbdMs0xrRGAsmKVm9VYC8bSTTuFhl");

        ObjectMetadata metadata = new ObjectMetadata();
        metadata.setContentType("application/octet-stream");

        ossClient.putObject("cozylux-produce", fileName, newPdfInputStream,metadata);
        Date expiration = new Date(System.currentTimeMillis() + 3600L * 1000 * 24 * 365 * 50);
        String url = ossClient.generatePresignedUrl("cozylux-produce", fileName, expiration).toString();

        // 关闭OSSClient。
        ossClient.shutdown();
        return url;
    }
}
